package com.chexiehui.jc.mvp.mine;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.base.ApiCallback;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BasePresenter;
import com.chexiehui.jc.utils.AliossUtil;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

/**
 * @Description 账号管理
 * @Auth SongJun
 * @Date 2019/03/28 15:11
 **/
public class AccountSettingPresenter extends BasePresenter<AccountSettingCovenant.View, AccountSettingCovenant.Stores>
        implements AccountSettingCovenant.Presenter {

    public AccountSettingPresenter(AccountSettingCovenant.View view) {
        attachView(view);
    }

    @Override
    public void updateAvatar(String filePath) {
        if (StringUtils.isTrimEmpty(filePath)) {
            mvpView.showToast("请上传头像");
            return;
        }
        mvpView.showLoading("正在保存");
        addSubscription(Observable.create((ObservableOnSubscribe<BaseModel<String>>) emitter -> {
            try {
                OSS ossClient = AliossUtil.createOssClient();
                final String[] tempArr = {""};
                String mObjectKeyPath = AliossUtil.createCarImagePath(filePath);
                // 异步构造上传请求  核心代码 就下面几行  再走阿里,上传给阿里
                PutObjectRequest objectRequest = new PutObjectRequest(AliossUtil.BUCKET_NAME, mObjectKeyPath, filePath);
                OSSAsyncTask<PutObjectResult> task = ossClient.asyncPutObject(objectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        LogUtils.e("Image---onSuccess", request.getObjectKey());
                        LogUtils.e("Image---onSuccess1", result.getServerCallbackReturnBody());
                        tempArr[0] = "/" + request.getObjectKey();
                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                        LogUtils.e("Image---onFailure", request.getObjectKey());
                        //videoUrl[0] = videoUrl[0] = "/" + request.getObjectKey();
                        if (emitter != null && !emitter.isDisposed()) {
                            emitter.onError(new Throwable("图片上传失败"));
                        }
                    }
                });
                task.waitUntilFinished();
                task.cancel();
                emitter.onNext(new BaseModel<>(0, "图片上传成功", tempArr[0]));
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }), new ApiCallback<BaseModel<String>>(mvpView) {
            @Override
            public void onSuccess(BaseModel<String> model) {
                doUpdateAvatar(model.getData());
            }

            @Override
            public void onFailure(int code, String msg) {
                mvpView.hide();
                mvpView.onUpdateAvatarFailure(new BaseModel<>(code, msg));
            }
        });
    }

    private void doUpdateAvatar(String url) {
        addSubscription(appStores.updateAvatar(url),
                new ApiCallback<BaseModel<String>>(mvpView) {
                    @Override
                    public void onSuccess(BaseModel<String> model) {
                        if (model.getResultCode() == 0) {
                            mvpView.hide();
                            model.setData(url);
                            mvpView.onUpdateAvatarSuccess(model);
                        } else {
                            onFailure(model.getResultCode(), model.getResultInfo());
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        mvpView.hide();
                        mvpView.onUpdateAvatarFailure(new BaseModel<>(code, msg));
                    }
                });
    }

    @Override
    public void updateName(String name) {
        if (StringUtils.isTrimEmpty(name)) {
            mvpView.showToast("用户名不能为空");
            return;
        }
        mvpView.showLoading("正在保存");
        addSubscription(appStores.updateName(name),
                new ApiCallback<BaseModel<String>>(mvpView) {
                    @Override
                    public void onSuccess(BaseModel<String> model) {
                        if (model.getResultCode() == 0) {
                            mvpView.hide();
                            model.setData(name);
                            mvpView.onUpdateNameSuccess(model);
                        } else {
                            onFailure(model.getResultCode(), model.getResultInfo());
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        mvpView.hide();
                        mvpView.onUpdateNameFailure(new BaseModel<>(code, msg));
                    }
                });
    }

    @Override
    public void updateRemark(String remark) {
        if (StringUtils.isTrimEmpty(remark)) {
            mvpView.showToast("介绍不能为空");
            return;
        }
        mvpView.showLoading("正在保存");
        addSubscription(appStores.updateRemark(remark),
                new ApiCallback<BaseModel<String>>(mvpView) {
                    @Override
                    public void onSuccess(BaseModel<String> model) {
                        if (model.getResultCode() == 0) {
                            mvpView.hide();
                            model.setData(remark);
                            mvpView.onUpdateRemarkSuccess(model);
                        } else {
                            onFailure(model.getResultCode(), model.getResultInfo());
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        mvpView.hide();
                        mvpView.onUpdateRemarkFailure(new BaseModel<>(code, msg));
                    }
                });
    }

    @Override
    public void updateBackgroundImg(String path) {
        if (StringUtils.isTrimEmpty(path)) {
            mvpView.showToast("请上传背景图");
            return;
        }
        mvpView.showLoading("正在保存");
        addSubscription(Observable.create((ObservableOnSubscribe<BaseModel<String>>) emitter -> {
            try {
                OSS ossClient = AliossUtil.createOssClient();
                final String[] tempArr = {""};
                String mObjectKeyPath = AliossUtil.createCarImagePath(path);
                // 异步构造上传请求  核心代码 就下面几行  再走阿里,上传给阿里
                PutObjectRequest objectRequest = new PutObjectRequest(AliossUtil.BUCKET_NAME, mObjectKeyPath, path);
                OSSAsyncTask<PutObjectResult> task = ossClient.asyncPutObject(objectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        LogUtils.e("Image---onSuccess", request.getObjectKey());
                        LogUtils.e("Image---onSuccess1", result.getServerCallbackReturnBody());
                        tempArr[0] = "/" + request.getObjectKey();
                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                        LogUtils.e("Image---onFailure", request.getObjectKey());
                        //videoUrl[0] = videoUrl[0] = "/" + request.getObjectKey();
                        if (emitter != null && !emitter.isDisposed()) {
                            emitter.onError(new Throwable("图片上传失败"));
                        }
                    }
                });
                task.waitUntilFinished();
                task.cancel();
                emitter.onNext(new BaseModel<>(0, "图片上传成功", tempArr[0]));
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }), new ApiCallback<BaseModel<String>>(mvpView) {
            @Override
            public void onSuccess(BaseModel<String> model) {
                doUpdateBackgroundImg(model.getData());
            }

            @Override
            public void onFailure(int code, String msg) {
                mvpView.hide();
                mvpView.onUpdateAvatarFailure(new BaseModel<>(code, msg));
            }
        });
    }

    private void doUpdateBackgroundImg(String url) {
        addSubscription(appStores.updateBackgroundImg(url),
                new ApiCallback<BaseModel<String>>(mvpView) {
                    @Override
                    public void onSuccess(BaseModel<String> model) {
                        if (model.getResultCode() == 0) {
                            mvpView.hide();
                            model.setData(url);
                            mvpView.onUpdateBackgroundImgSuccess(model);
                        } else {
                            onFailure(model.getResultCode(), model.getResultInfo());
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        mvpView.hide();
                        mvpView.onUpdateBackgroundImgFailure(new BaseModel<>(code, msg));
                    }
                });
    }

}